package club.jdiy.core.job.service.impl;

import club.jdiy.core.base.JDiyBaseService;
import club.jdiy.core.ex.JDiyFormException;
import club.jdiy.core.job.entity.JDiyJob;
import club.jdiy.core.job.exec.CronUtils;
import club.jdiy.core.job.exec.JobHandler;
import club.jdiy.core.job.exec.ScheduleUtils;
import club.jdiy.core.job.dao.JDiyJobDao;
import club.jdiy.core.job.service.JDiyJobService;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
public class JDiyJobServiceImpl extends JDiyBaseService<JDiyJob, JDiyJobDao, Long>
        implements JDiyJobService {
    @Override
    @SuppressWarnings("unchecked")
    @Transactional
    public JDiyJob save(JDiyJob vo) {
        if (!CronUtils.isValid(vo.getJobCron())) {
            throw new JDiyFormException("任务调度(Cron表达式)输入格式不正确！" +
                    CronUtils.getInvalidMessage(vo.getJobCron()), "jobCron");
        }

        try {
            JobHandler.testJobExecute(context, vo);
        } catch (Exception ex) {
            throw new JDiyFormException("您输入的任务执行代码有误：" + ex, "jobExecute");
        }

        JDiyJob po = dao.findById(vo.getId()).orElseGet(() -> new JDiyJob(vo.getJobName(), vo.getJobGroup()));
        po.setJobCron(vo.getJobCron());
        po.setJobExecute(vo.getJobExecute());
        po.setJobPause(Boolean.TRUE.equals(vo.getJobPause()));
        po.setJobLog(Boolean.TRUE.equals(vo.getJobLog()));
        po.setJobConcurrent(Boolean.TRUE.equals(vo.getJobConcurrent()));
        po.setJobMisfire(vo.getJobMisfire());
        po.setJobRemark(vo.getJobRemark());
        po = dao.save(po);
        ScheduleUtils.createScheduleJob(scheduler, po);
        return po;
    }

    @Override
    @Transactional
    public void delete(JDiyJob job) {
        try {
            scheduler.deleteJob(ScheduleUtils.getJobKey(job));
            super.delete(job);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void runById(Long jobId) throws SchedulerException {
        dao.findById(jobId).ifPresent(po ->{
            try {
                scheduler.triggerJob(ScheduleUtils.getJobKey(po));
            } catch (SchedulerException e) {
                e.printStackTrace();
            }
        });
    }

    @Resource
    private Scheduler scheduler;
}
